/**
 * 
 */
package com.behealthy.android;

import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.behealthy.util.StringUtils;
import com.behealthy.util.Utility;
import com.example.behealthy.R;
import com.facebook.android.Facebook;
import com.facebook.android.LoginButton;
import com.facebook.android.SessionEvents;
import com.facebook.android.SessionEvents.AuthListener;
import com.facebook.android.SessionStore;

/**
 * @author Monica
 *
 */
public class BeHealthyLoginActivity extends Activity {

	private String url = "http://192.168.33.103:8080/TestDao/WsTest?wsdl";
//	private String url = "http://10.0.2.2:8080/TestDao/WsTest?wsdl";
	
	// Facebook APP ID
	private static String App_ID = "474982679242477";

	// Instance of Facebook class
	private Facebook facebook;

	String filename = "App_data";

	// Tag name for LogCat messages
	private String TAG = "BeHealthyLoginActivity";

	// Instance of shared preferences
	String PREFS = "MyPrefs";
	private SharedPreferences sharedPrefs;
	
	private String[] permissions = {"user_photos", "publish_stream", "read_stram", "email" };
	
	private Context context;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.login);

		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		context = this;
		sharedPrefs = getSharedPreferences(PREFS, 0);
				
		if(!this.CheckEnableInternet()) {
			 final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
	        	alertDialog.setTitle(StringUtils.INTERNET);
	        	alertDialog.setMessage(StringUtils.INTERNET_OFF);
	        	alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
	        		public void onClick( DialogInterface dialog, int which) {
	        			dialog.dismiss();
	        			Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
	        		    startActivity(intent);
	        		}
	        	});
	        	alertDialog.show();	
		 }
		 else { 
			 Toast.makeText(getApplicationContext(), StringUtils.INTERNET_ON, Toast.LENGTH_SHORT).show();
		 }

		facebook = new Facebook(App_ID);
		SessionStore.restore(facebook, this);
		
		LoginButton facebookButton = (LoginButton) findViewById(R.id.btnFacebook);
		Button loginButton = (Button) findViewById(R.id.btnLogin);
		TextView registerScreen = (TextView) findViewById(R.id.link_to_register);

		final EditText username  = (EditText) findViewById(R.id.username);
		final EditText password = (EditText) findViewById(R.id.password);
		final CheckBox remember = (CheckBox) findViewById(R.id.rememberMe);
		final AlertDialog alertDialog = new AlertDialog.Builder(this).create();

//		Check if the remember me option has been checked before
		boolean rememberMe = sharedPrefs.getBoolean("rememberMe", false);

		if (rememberMe == true) {
			// Get previous login information
			String user = sharedPrefs.getString("userName", null);
			String userPass = sharedPrefs.getString("userPassword", null);

			if (user!= null && userPass != null) {
				// Fill input EditText with stored email and password
				username.setText(user);
				password.setText(userPass);

				// Set the remember me CheckBox to 'checked'
				remember.setChecked(true);
			}
		}

		if (facebook.isSessionValid()) {
			Intent j = new Intent(getApplicationContext(), BeHealthyMainActivity.class);
			j.putExtra("session", true);
			startActivity(j);
		} else {
			SessionEvents.addAuthListener(new FacebookAuthListener());
			facebookButton.init(this, this.facebook, this.permissions, facebook.isSessionValid());
			
			// Listening to register new account link
			registerScreen.setOnClickListener(new Button.OnClickListener() {
				public void onClick(View v) {
					// Switching to Register screen
					Intent i = new Intent(getApplicationContext(),
							BeHealthyRegisterActivity.class);
					startActivity(i);
				}
			});


			// Listening to login link
			loginButton.setOnClickListener(new Button.OnClickListener() {
				public void onClick(View v) {
					 v.setEnabled(false);
				     AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() 
				    		 {
			                private ProgressDialog pd;
			                @Override
			                protected void onPreExecute() {
			                         pd = new ProgressDialog(context);
			                         pd.setTitle("Processing...");
			                         pd.setMessage("Please wait.");
			                         pd.setCancelable(false);
			                         pd.setIndeterminate(true);
			                         pd.show();
			                }
			                @Override
			                protected Void doInBackground(Void... arg0) {
			                        try {
			                        	if (username.getText().toString().equals("")
			        							|| password.getText().toString().equals("")) {
			        						alertDialog.setTitle(StringUtils.ERR);
			        						alertDialog.setMessage(StringUtils.ERR_COMPULSORY);
			        						alertDialog.setButton("OK",
			        								new DialogInterface.OnClickListener() {
			        									public void onClick(DialogInterface dialog,
			        											int which) {
			        									}
			        								});
			        						alertDialog.show();
			        					} else {
			        						
			        						String usernameStr = username.getText().toString();
			        						String passwordStr = password.getText().toString();
			        						String passwordEncrypt = null;
			        						
			        						if (remember.isChecked())
			        							saveLoginDetails(usernameStr, passwordStr);
			        						else
			        							removeLoginDetails();

			        						

			        						MessageDigest md;
			        						try {
			        							md = MessageDigest.getInstance("MD5");
			        							md.update(passwordStr.getBytes(), 0,
			        									passwordStr.length());
			        							passwordEncrypt = new BigInteger(1, md.digest())
			        									.toString(16);
			        						} catch (NoSuchAlgorithmException e) {
			        							e.printStackTrace();
			        						}

			        						String envelope = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
			        								+ "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "
			        								+ "xmlns:ws=\"http://ws.android/\">"
			        								+ "<soapenv:Header/>"
			        								+ "<soapenv:Body>"
			        								+ "<ws:login>"
			        								+ "<person><firstName/><lastName/><email/><birthDate/></person>"
			        								+ "<username>%s</username>"
			        								+ "<password>%s</password>"
			        								+ "</ws:login>"
			        								+ "</soapenv:Body>" 
			        								+ "</soapenv:Envelope>";
			        						
			        						String requestEnvelope = String.format(envelope, 
			        								usernameStr, passwordEncrypt);
			        						String soapAction = "login";
			        						String response = "message";

			        						response = Utility.CallWebService(url, soapAction,
			        								requestEnvelope);

			        						Log.d("Response", response);

			        						String s = "";
			        						try {
			        							s = Utility.parseByDOM(response, "loginResponse");
			        						} catch (ParserConfigurationException e) {

			        							e.printStackTrace();
			        						} catch (SAXException e) {

			        							e.printStackTrace();
			        						} catch (IOException e) {

			        							e.printStackTrace();
			        						}
			        						if (s.equals("true")) {

			        							Intent j = new Intent(getApplicationContext(),
			        									BeHealthyMenuActivity.class);
			        							j.putExtra("username", usernameStr);
			        														
			        							startActivity(j);
			        							
			        						} else {

			        							alertDialog.setTitle(StringUtils.ERR);
			        							alertDialog.setMessage(s);
			        							alertDialog.setButton("OK",
			        									new DialogInterface.OnClickListener() {
			        										public void onClick(
			        												DialogInterface dialog,
			        												int which) {
			        										}
			        									});
			        							alertDialog.show();
			        						}

			        					}
			                        	
			                               Thread.sleep(5000);
			                        } catch (InterruptedException e) {
			                               // TODO Auto-generated catch block
			                               e.printStackTrace();
			                        }
			                        return null;
			                 }
			                 @Override
			                 protected void onPostExecute(Void result) {
			                         pd.dismiss();
			                         findViewById(R.id.btnLogin).setEnabled(true);
			                 }
			        };
			        task.execute((Void[])null);
				}
			});
		}
	}

	private void saveLoginDetails(String username, String password) {
		
		Editor e = sharedPrefs.edit();
		e.putBoolean("rememberMe", true);
		e.putString("userName", username);
		e.putString("userPassword", password);
		e.commit();
	}

	private void removeLoginDetails() {
		Editor e = sharedPrefs.edit();
		e.putBoolean("rememberMe", false);
		e.remove("userName");
		e.remove("userPassword");
		e.commit();
	}

	private boolean CheckEnableInternet() {
		
		Log.d("Internet", "Internet method");
		
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getNetworkInfo(1), ni2 = cm.getNetworkInfo(0);
		
		if( cm !=null && ((ni.getState() == NetworkInfo.State.CONNECTED) || (ni2.getState() == NetworkInfo.State.CONNECTED))) {
//			Connected 
			Log.d("Internet", "Internet method+1");
			return true;
		}
		else if(ni.getState() == NetworkInfo.State.DISCONNECTED || ni2.getState() == NetworkInfo.State.DISCONNECTED ) 
		{	Log.d("Internet", "Internet method+2");
//			Not connected
			return false;	
		}
		return false;
	}

	private class FacebookAuthListener implements AuthListener {
		public void onAuthSucceed() {
			Log.d(TAG, "onAuthSucceed");
			
			Intent j = new Intent(getApplicationContext(), BeHealthyMainActivity.class);
			Intent k = new Intent(getApplicationContext(), BeHealthyRegisterActivity.class);
			if (facebook.isSessionValid()) {
				j.putExtra("session", true);
				k.putExtra("facebookLogin", true);
			}
			else {
				j.putExtra("session", false);
				k.putExtra("facebookLogin", false);
			}
			startActivity(j);

		}

		public void onAuthFail(String error) {
			Log.d(TAG, "FacebookError: Login failed");
		}

	}
}
